package org.feifei.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.feifei.basic.constant.LoginConstant;
import org.feifei.basic.constant.VerifyConstant;
import org.feifei.basic.exception.BusinessException;
import org.feifei.basic.service.impl.BaseServiceImpl;
import org.feifei.basic.util.CommonResult;
import org.feifei.basic.util.MD5Utils;
import org.feifei.basic.util.StrUtils;
import org.feifei.user.constant.WxUserConstant;
import org.feifei.user.domain.LoginInfo;
import org.feifei.user.domain.User;
import org.feifei.user.domain.WxUser;
import org.feifei.user.dto.LoginDTO;
import org.feifei.user.mapper.LoginInfoMapper;
import org.feifei.user.mapper.UserMapper;
import org.feifei.user.mapper.WxUserMapper;
import org.feifei.user.service.LoginInfoService;
import org.feifei.user.util.HttpClientUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.sql.Time;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * LoginInfoService 的实现类
 */
@Transactional(readOnly = false, propagation = Propagation.SUPPORTS)
@Service
public class LoginInfoServiceImpl extends BaseServiceImpl<LoginInfo> implements LoginInfoService {

    @Resource
    private LoginInfoMapper loginInfoMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    @Resource
    private WxUserMapper wxUserMapper;

    @Override
    public CommonResult<Map<String, Object>> login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        Integer loginType = loginDTO.getLoginType();
        // 非空判断
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password) || !StringUtils.hasText(String.valueOf(loginType)) ) {
            throw new BusinessException("请输入合法信息!");
        }
        // 根据用户名和状态码查询对象
        LoginInfo loginInfoDB = loginInfoMapper.findLoginInfo(loginDTO);
        if (loginInfoDB == null) {
            throw new BusinessException("用户名或者密码错误！");
        }
        // 判断密码是否一致
        if (!loginInfoDB.getPassword().equals(MD5Utils.encrypByMd5(loginInfoDB.getSalt() + password))) {
            throw new BusinessException("用户名或者密码错误！");
        }
        // 判断该账号是否可用
        if (!loginInfoDB.getDisable()) {
            throw new BusinessException("当前账户存在问题，请联系客服解决问题");
        }
        // 将token保存到redis中 30分钟有效
        // 获取token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, loginInfoDB, 30, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>();
        map.put(LoginConstant.LOGIN_TOKEN_KEY, token);
        loginInfoDB.setSalt(null).setPassword(null);
        map.put(LoginConstant.LOGIN_INFO , loginInfoDB);
        return CommonResult.ok(map);
    }

    @Override
    public CommonResult WxUserLogin(Map<String, String> map) {
        String code = map.get(WxUserConstant.CODE);
        String url = WxUserConstant.GET_ACK_URL.replace("APPID", WxUserConstant.APPID).replace("SECRET", WxUserConstant.SECRET)
                .replace("CODE", code);
        String jsonStr = HttpClientUtils.httpGet(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObject.toJSONString()+"----------------");
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        System.out.println(openid);
        WxUser wxUser = wxUserMapper.findByOpenId(openid);
        Map<String, Object> WxMap = new HashMap<>();
        if ( wxUser != null && wxUser.getUser_id() != null) {
            LoginInfo logininfo = loginInfoMapper.findByUserId(wxUser.getUser_id());
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            WxMap.put(LoginConstant.LOGIN_TOKEN_KEY,token);
            logininfo.setPassword("").setSalt("");
            WxMap.put(LoginConstant.LOGIN_INFO, logininfo);
            return CommonResult.ok(WxMap);
        } else {
            WxMap.put("access_token",access_token);
            WxMap.put("openid",openid);
            return CommonResult.failure(WxMap);
        }
    }

    @Override
    public CommonResult wxUserBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        // 非空判断
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(verifyCode) ) {
            throw new BusinessException("请输入合法信息!");
        }
        System.out.println(VerifyConstant.Binder_CODE_PREFIX + phone);
        // 获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(VerifyConstant.Binder_CODE_PREFIX + phone);

        if (redisCode == null ) {
            throw new BusinessException("验证码过期");
        }

        // 判断验证码是否一致
        String code = redisCode.split(VerifyConstant.VERIFY_SEPARATOR)[0];
        if (!verifyCode.equals(code)) {
            throw new BusinessException("验证码输入错误请重新输入");
        }
        User user = userMapper.findUserByPhone(phone);
        String getWxUserUrl = WxUserConstant.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        String WxUserStr = HttpClientUtils.httpGet(getWxUserUrl);
        WxUser wxUser = wxUserStr2WxUser(WxUserStr);
        if (user == null) {
             user = phone2User(phone);
             LoginInfo loginInfo = user2loginInfo(user);
             loginInfoMapper.save(loginInfo);
             user.setLogininfo_id(loginInfo.getId());
             userMapper.save(user);
        }
        wxUser.setUser_id(user.getId());
        wxUserMapper.save(wxUser);

        LoginInfo loginInfo = loginInfoMapper.findByUserId(wxUser.getUser_id());
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, loginInfo, 30 , TimeUnit.MINUTES);
        Map<String, Object> wxMap = new HashMap<>();
        wxMap.put("token",token);
        wxMap.put("loginInfo", loginInfo.setSalt(null).setPassword(null));
        return CommonResult.ok(wxMap);

    }

    @Override
    public CommonResult accountByPhone(Map<String, Object> map) {
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        // 非空判断
        if (!StringUtils.hasText(phone) || !StringUtils.hasText(code)) {
            throw new BusinessException("请输入合法信息!");
        }
        LoginInfo loginInfo = loginInfoMapper.findByPhone(phone);
        if (loginInfo == null) {
            throw new BusinessException("该手机号为注册，请前往注册");
        }
        // 将token保存到redis中 30分钟有效
        // 获取token
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        Map<String, Object> Phonemap = new HashMap<>();
        Phonemap.put(LoginConstant.LOGIN_TOKEN_KEY, token);
        loginInfo.setSalt(null).setPassword(null);
        Phonemap.put(LoginConstant.LOGIN_INFO , loginInfo);
        return CommonResult.ok(Phonemap);
    }

    /**
     * 复制 员工user的信息 到 logininfo登录信息表
     * @param user
     * @return
     */
    private LoginInfo user2loginInfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user, loginInfo);
        loginInfo.setType(1); // 1 表示用户
        return loginInfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //密码：随机
        String md5Pwd = MD5Utils.encrypByMd5(StrUtils.getComplexRandomString(6) + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private WxUser wxUserStr2WxUser(String wxUserStr) {
        WxUser wxUser = JSONObject.parseObject(wxUserStr, WxUser.class);
        JSONObject jsonObject = JSONObject.parseObject(wxUserStr);
        String address = jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city");
        wxUser.setAddress(address);
        return wxUser;
    }
}
